package com.ant.user.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import static com.ant.user.utils.SignatureUtils.*;
import static java.util.Base64.getUrlDecoder;

//对称加密
//@Component
@Service
public class JWTService {
    @Value("${app.login-exceed}")
    long loginTime;

    @Value("${app.key.publicPath}")
    String publicKeyPath;

    @Value("${app.key.privatePath}")
    String privateKeyPath;

    public void printInjectData()
    {
        System.out.println(loginTime);
        System.out.println(privateKeyPath);
        System.out.println(publicKeyPath);
    }

    public  String getToken(Map<String,String> payload) throws IOException, NoSuchAlgorithmException,
            InvalidKeySpecException, SignatureException, InvalidKeyException {
        Map<String, String> header = new HashMap<>();
        header.put("algorithm", "SHA256withRSA");
        header.put("type", "jwt");
        String headData = Base64.getUrlEncoder().withoutPadding().encodeToString(JSON.toJSONString(header).getBytes());
        String payloadData = Base64.getUrlEncoder().withoutPadding().encodeToString(JSON.toJSONString(payload).getBytes());

        PrivateKey privateKey = loadPrivateKey(privateKeyPath);
        String data = headData + "." + payloadData;
        return data + "." + GenerateSignature(data, privateKey);
    }


    /**
     * 解析token
     * @param token token字符串
     * @return 解析后的token
     */
    public  boolean verifyToken(String token) throws IOException, NoSuchAlgorithmException,
            InvalidKeySpecException, SignatureException, InvalidKeyException {
        PublicKey publicKey = loadPublicKey(publicKeyPath);
        String[] parts = token.split("\\.");
        return VerifySignature(parts[0] + "." + parts[1], publicKey, parts[2]);
    }

    public  Map<String, String> decodeToken(String jwt)
    {
        Map<String, String> result = null;
        String payload = new String(getUrlDecoder().decode(jwt.split("\\.")[1]));
        result = JSON.parseObject(payload, new TypeReference<>() {});

        return result;
    }
}

